import React                    from 'react';
import {connect}                from "react-redux";

import QR                       from '../../components/icon/QR';
import Nav                      from '../../config/Navigator';
import Base                     from '../../components/BaseComponent';
import Shop                     from '../../components/icon/Shop';
import Empty                    from '../../components/form/Empty';
import PullUp                   from '../../components/form/PullUp';
import BarCode                  from '../../components/form/BarCode';
import {Tabs, Tab}              from '../../components/nav/Tabs';
import {BottomNav, Button}      from '../../components/nav/BottomNav';
import {
    loadNew,
    loadUsed,
    loadCount,
    loadExpire,
}                               from "../../actions/voucher";
import './voucher.scss';

const TABS = {
    NEW: 'new',
    USED: 'used',
    EXPIRE: 'expire',
};

class Voucher extends Base {

    state = {
        openId: '',
        newList: [],
        newTotal: '',
        usedList: [],
        usedTotal: '',
        expireList: [],
        expireTotal: '',
    };

    tab = TABS.NEW;
    interval;
    page = {
        size: 10,
        index: 1,
    };

    _reset(){
        this.page.index = 1;
        this.close();
        this.setState({openId: ''});
    }

    _load(tab){
        this._reset();
        this.props[`load${_.upperFirst(tab)}`](this.page).then(({total, list}) => {
            this.setState({[`${tab}Total`]: total, [`${tab}List`]: list});
        });
    }

    _reload(){
        var _total = `${this.tab}Total`, _list = `${this.tab}List`, {[_total]: Total, [_list]: List} = this.state;
        if(List.length < Total){
            this.page.index++;
            return this.props[`load${_.upperFirst(this.tab)}`](this.page).then(({total, list}) => {
                this.setState({[_total]: total, [_list]: List.concat(list)});
            });
        }
    }

    componentWillMount(){
        document.title = '我的代金券';
        this._load(TABS.NEW);
        this._load(TABS.USED);
        this._load(TABS.EXPIRE);
    }

    changeTab(tab){
        this._load(this.tab = tab);
    }

    open(m){
        if(this.state.openId !== m.id){
            this.interval = setInterval(() => {
                this.props.loadCount(m).then(c => {
                    if (m.count !== parseInt(c)) {
                        this.alert('使用成功');
                        this._load(this.tab);
                    }
                })
            }, 1000);
        }
    }

    close(){
        var {openId} = this.state;
        if(!_.isEmpty(openId)){
            clearInterval(this.interval);
        }
    }

    toggle(m){
        var {openId} = this.state;
        this.close();
        this.open(m);
        this.setState({openId: openId === m.id ? '' : m.id});
    }

    render(){
        var {openId, newList, newTotal, usedList, usedTotal, expireList, expireTotal} = this.state;
        return (
            <div className="voucher">
                <div className="v-main">
                    <Tabs init={this.tab} onChange={this.changeTab.bind(this)}>
                        <Tab key={TABS.NEW} title={`未使用(${newTotal})`}>
                            <Empty list={newList} type={TABS.NEW}>
                                <PullUp load={this._reload.bind(this)}>
                                    {newList.map(m =>
                                        <div key={m.id} className="ticket">
                                            <div className="tic-body">
                                                <TicketHead item={m}/>
                                                <div className="tic-right flex-avg">
                                                    <div className="tic-detail">
                                                        <div className="tic-d-name">{m.name}</div>
                                                        <span>{m.limitPrice}</span>
                                                        <span>{m.time}</span>
                                                    </div>
                                                    <div className="tic-cart tic-c-use flex-avg" onClick={() => this.toggle(m)}>
                                                        <div>立即</div>
                                                        <div>使用</div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div className={`using${m.id === openId ? '' : ' hide'}`}>
                                                <div className="vu-title">{m.name}</div>
                                                <div className="vu-title">{m.limitPrice}</div>
                                                <div className="vu-qr flex-avg">
                                                    <BarCode value={m.qr}/>
                                                    <span>×{m.count}</span>
                                                </div>
                                                <TicketFoot item={m}/>
                                            </div>
                                        </div>
                                    )}
                                </PullUp>
                            </Empty>
                        </Tab>
                        <Tab key={TABS.USED} title={`已使用(${usedTotal})`}>
                            <Empty list={usedList} type={TABS.USED}>
                                <PullUp load={this._reload.bind(this)}>
                                    {usedList.map((m, i) =>
                                        <div key={i} className="ticket">
                                            <div className="tic-body">
                                                <TicketHead item={m} className="stamp-gray"/>
                                                <div className="tic-right flex-avg">
                                                    <div className="tic-detail">
                                                        <span>{m.name}</span>
                                                        <span>{m.limitPrice}</span>
                                                        <span>已使用：{m.count}个</span>
                                                        <span>消费时间：{m.time}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                </PullUp>
                            </Empty>
                        </Tab>
                        <Tab key={TABS.EXPIRE} title={`已过期(${expireTotal})`}>
                            <Empty list={expireList} type={TABS.EXPIRE}>
                                <PullUp load={this._reload.bind(this)}>
                                    {expireList.map((m, i) =>
                                        <div key={i} className="ticket">
                                            <div className="tic-body">
                                                <TicketHead item={m} className="stamp-gray"/>
                                                <div className="tic-right flex-avg">
                                                    <div className="tic-detail">
                                                        <span>{m.name}</span>
                                                        <span className="tic-expire">已过期：{m.count}</span>
                                                        <span>过期时间：{m.time}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                </PullUp>
                            </Empty>
                        </Tab>
                    </Tabs>
                </div>
                <BottomNav>
                    <Button label="兑换商城" to={Nav.cartList()} icon={<Shop />}/>
                    <Button label="我的二维码" to={Nav.qr()} icon={<QR />}/>
                </BottomNav>
            </div>
        );
    }

}

export const TicketHead = ({item, className = 'stamp'}) => (
    <div className={`tb-header ${className}`}>
        <div>{item.price < 1 ? '积分商品' : '代金券'}</div>
        <div className="tbh-price">
            <span>{item.price}</span>元
        </div>
    </div>
);

export const TicketFoot = ({item}) => (
    <React.Fragment>
        <div className="vu-sec">
            {item.accumPrinciple}
            {_.map(item.accumRule, (r, i) => <div key={i}>{r}</div>)}
        </div>
        {_.map(item.accumRange, (m, i) => <div key={i} className="vu-sec vu-gray">{m}</div>)}
    </React.Fragment>
);

export default connect(undefined, {loadNew, loadUsed, loadExpire, loadCount})(Voucher);
